package com.ogawa.a7517.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.Group;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.easepal.softaplib.wifi.WiFiManager;
import com.example.reslib.Constants;
import com.example.reslib.utils.PreferenceWrapper;
import com.example.reslib.utils.ToastUtils;
import com.example.reslib.view.kprogresshud.KProgressHUD;
import com.ogawa.a7517.Constant;
import com.ogawa.a7517.DataManager;
import com.ogawa.a7517.R;
import com.ogawa.a7517.bean.DeviceOffBean;
import com.ogawa.a7517.bean.DeviceStateBean;
import com.ogawa.a7517.bean.MassageArmchair;
import com.ogawa.a7517.fragment.AdjustFragment;
import com.ogawa.a7517.fragment.AutoMassageFragment;
import com.ogawa.a7517.fragment.BaseFragment;
import com.ogawa.a7517.fragment.BodyTypeFragment;
import com.ogawa.a7517.fragment.FactoryModeFragment;
import com.ogawa.a7517.fragment.FaultFragment;
import com.ogawa.a7517.fragment.LeadPageFragment;
import com.ogawa.a7517.fragment.MainFragment;
import com.ogawa.a7517.fragment.SeniorMassageFragment;
import com.ogawa.a7517.fragment.SettingFragment;
import com.ogawa.a7517.fragment.ShoulderCheckFragment;
import com.ogawa.a7517.fragment.WifiNetFragment;
import com.ogawa.a7517.mqtt.MqttConnectListener;
import com.ogawa.a7517.mqtt.MqttDeviceStateListener;
import com.ogawa.a7517.mqtt.MqttManager;
import com.ogawa.a7517.mqtt.MqttSendMsgCallback;
import com.ogawa.a7517.widget.ShutdownDialog;
import com.ogawa.networklib.RetrofitManager;
import com.ogawa.networklib.RxObserver;
import com.ogawa.networklib.networkBean.BaseResponseBean;
import com.ogawa.networklib.networkBean.MqttAccountBean;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;

import java.util.Locale;

public class MainActivity7517 extends RxAppCompatActivity implements View.OnClickListener
        , MqttSendMsgCallback, MqttConnectListener, MqttDeviceStateListener {
    private FragmentManager manager;
    private BaseFragment currentFragment;
    private boolean isResume;
    private TextView tvTitle;
    private ShutdownDialog shutdownDialog;
    private KProgressHUD waitProgress;// 等待进度条
    private ImageView ivPower, ivPause, ivHome, ivAdjust, ivSetting, ivCurrent;
    private String mqttAccount, mqttPsw;
    private int running, currentAuto;
    private boolean inBodyType, inShoulderType, inSenior, isInFault;
    private Dialog safetyDialog;
    private Dialog childLockDialog;
    private Group groupMain;
    private boolean isShowSafe, isShowLock;
    private AlertDialog noDeviceDialog;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_7517);
        DataManager.getInst().setActivity(this);
        DataManager.getInst().initPrograms(this);
        groupMain = findViewById(R.id.group_main);
        manager = getSupportFragmentManager();
        tvTitle = findViewById(R.id.tv_title);
        ivPower = findViewById(R.id.iv_power);
        ivPower.setOnClickListener(this);
        ivPause = findViewById(R.id.iv_pause);
        ivPause.setOnClickListener(this);
        ivHome = findViewById(R.id.iv_home);
        ivHome.setOnClickListener(this);
        ivAdjust = findViewById(R.id.iv_adjust);
        ivAdjust.setOnClickListener(this);
        ivSetting = findViewById(R.id.iv_setting);
        ivSetting.setOnClickListener(this);
        ivCurrent = ivHome;
        waitProgress = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
        if (savedInstanceState == null) {
            MqttManager.getInstance().initClient(this);
        } else {
            mqttAccount = savedInstanceState.getString("mqttAccount", "");
            mqttPsw = savedInstanceState.getString("mqttPsw", "");
            running = savedInstanceState.getInt("running", running);
            currentAuto = savedInstanceState.getInt("currentAuto", currentAuto);
            inBodyType = savedInstanceState.getBoolean("inBodyType", inBodyType);
            inShoulderType = savedInstanceState.getBoolean("inShoulderType", inShoulderType);
            inSenior = savedInstanceState.getBoolean("inSenior", inSenior);
            isInFault = savedInstanceState.getBoolean("isInFault", isInFault);
        }
        MqttManager.getInstance().setMqttConnectListener(this);//注册连接监听
        MqttManager.getInstance().registerMqttDeviceStateListener(this);//注册状态监听
        MqttManager.getInstance().registerMqttSendMsgCallback(this);//注册发送信息结果监听
        boolean firstIn = getIntent().getBooleanExtra(Constant.FIRST_IN, false);
        if (firstIn) {
            startToFragmentAddToStack(new LeadPageFragment());
        } else {
            Bundle bundle = new Bundle();
            bundle.putBoolean("reset", savedInstanceState != null);
            startToFragmentAddToStack(new MainFragment(), bundle);
        }
    }

    public void setCurrentFragment(BaseFragment fragment) {
        currentFragment = fragment;
        ivCurrent.setSelected(false);
        if (currentFragment instanceof MainFragment) {
            ivCurrent = ivHome;
        } else if (currentFragment instanceof AdjustFragment) {
            ivCurrent = ivAdjust;
        } else if (currentFragment instanceof SettingFragment) {
            ivCurrent = ivSetting;
        }
        if (currentFragment instanceof FactoryModeFragment
                || currentFragment instanceof LeadPageFragment
                || currentFragment instanceof FaultFragment) {
            groupMain.setVisibility(View.GONE);
        } else {
            groupMain.setVisibility(View.VISIBLE);
        }
        ivCurrent.setSelected(true);
    }

    public void publish(String func, String model, String addition) {
        if (MqttManager.getInstance().isConnect()) {//已连接
            boolean isQuery = Constant.RUNNING_STATUS_QUERY.equals(func);
            boolean isPower = Constant.RUNNING_STATUS.equals(func) && ("0".equals(model) || "1".equals(model));
            boolean isPause = Constant.RUNNING_STATUS.equals(func) && "5".equals(model);
            boolean isZero = Constant.ZERO_GRAVITY.equals(func);
            boolean isBackLeg = Constant.BACK_LEG_POS_ADJUST.equals(func);
            boolean isLeg = Constant.LEG_POS_ADJUST.equals(func);
            boolean isLegX = Constant.LEG_POS_ADJUST_X.equals(func);
            boolean isFactory = Constant.PROJECT_MODE.equals(func);
            boolean isAntiPinch = Constant.ANTI_PINCH_CHECK.equals(func);
            if (!isQuery && !isPower && !isZero && !isBackLeg
                    && !isLeg && !isLegX && !ivPower.isSelected() && !isFactory && !isAntiPinch) {//未开机
                ToastUtils.showShortToast(this, getString(R.string.power_tip));
                return;
            }
            if (!isQuery && !isPause && ivPause.isSelected() && !isPower) {//已暂停
                ToastUtils.showShortToast(this, getString(R.string.cancel_pause_tip));
                return;
            }
            if (!(currentFragment instanceof WifiNetFragment)) {
                showWaitDialog(R.string.waiting);
            }
            MqttManager.getInstance().publish(func, model, addition);
        } else {//未连接
            connectMqtt(false);
        }
    }

    public void publish(String func, String model) {
        publish(func, model, null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        String currentSSID = WiFiManager.getInstance(this).getConnectionInfo()
                .getSSID().replaceAll("\"", "");
        if (!MqttManager.getInstance().isConnect()) {//如果Mqtt未连接，则尝试连接（防止Mqtt断开）
            if (!Constant.AUTO_LINK_SSID.equals(currentSSID)) {
                connectMqtt(true);
            }
        }
        onDeviceStateChange();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataManager.getInst().setActivity(null);
        MqttManager.getInstance().unRegisterMqttDeviceStateListener(this);
        MqttManager.getInstance().unRegisterMqttSendMsgCallback(this);
        MqttManager.getInstance().clearMqttConnectListener();
    }

    private void showShutdownDialog() {
        if (shutdownDialog == null) {
            shutdownDialog = new ShutdownDialog(this);
        }
        shutdownDialog.show();
    }

    public void setTitle(String title) {
        tvTitle.setText(title);
    }

    /**
     * 启动Fragment,并将Fragment加入回退栈中
     *
     * @param newFragment
     */
    public void startToFragmentAddToStack(Fragment newFragment) {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fr_content, newFragment);
        transaction.addToBackStack(newFragment.getClass().getName());
        transaction.commitAllowingStateLoss();
    }

    /**
     * 附带信息启动Fragment,并将Fragment加入回退栈中
     *
     * @param newFragment
     */
    public void startToFragmentAddToStack(Fragment newFragment, Bundle bundle) {
        FragmentTransaction transaction = manager.beginTransaction();
        if (bundle != null) {
            newFragment.setArguments(bundle);
        }
        transaction.replace(R.id.fr_content, newFragment);
        transaction.addToBackStack(newFragment.getClass().getName());
        transaction.commitAllowingStateLoss();
    }

    /**
     * 返回上一个Fragment
     */
    public void popBackStack() {
        if (isResume && manager.getBackStackEntryCount() > 1) {
            manager.popBackStack();
        }
    }

    /**
     * @param name 返回到指定Fragment的名称
     * @param flag 移走栈中Fragment的方式，0表示把自己之前的弹出，1表示把自己也弹出
     */
    public void popBackStack(String name, int flag) {
        if (isResume) {
            manager.popBackStack(name, flag);
        }
    }

    public boolean isSnExist() {
        String sn = new PreferenceWrapper().getStringValue(Constant.SN_7517, "");
        if (TextUtils.isEmpty(sn)) {
            showNoDeviceDialog();
            return false;
        }
        return true;
    }

    private void showNoDeviceDialog() {
        if (noDeviceDialog == null) {
            noDeviceDialog = new AlertDialog
                    .Builder(this)
                    .setTitle(R.string.tip)
                    .setMessage(R.string.no_device_tip)
                    .setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
                        startToFragmentAddToStack(new WifiNetFragment());
                    }).setNegativeButton(R.string.cancle, null)
                    .setCancelable(false)
                    .create();
        }
        noDeviceDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_power) {
            if (!isSnExist()) {
                return;
            }
            if (MqttManager.getInstance().isConnect()) {
                if (v.isSelected()) {
//                    showShutdownDialog();
                    publish(Constant.RUNNING_STATUS, "0");
                } else {
                    if (MassageArmchair.getInstance().getReset() == 1) {
                        publish(Constant.RUNNING_STATUS, "1");
                    } else {
                        ToastUtils.showShortToast(this, getString(R.string.movement_resetting_tip));
                    }
                }
            } else {
                connectMqtt(false);
            }

        } else if (v.getId() == R.id.iv_pause) {
            if (!isSnExist()) {
                return;
            }
            publish(Constant.RUNNING_STATUS, "5");
        } else if (v.getId() == R.id.iv_home) {
            popBackStack(MainFragment.class.getName(), 0);
        } else if (v.getId() == R.id.iv_adjust) {
            if (!isSnExist()) {
                return;
            }
            if (currentFragment instanceof AdjustFragment) {
                return;
            }
            startToFragmentAddToStack(new AdjustFragment());
        } else if (v.getId() == R.id.iv_setting) {
            if (currentFragment instanceof SettingFragment) {
                return;
            }
            startToFragmentAddToStack(new SettingFragment());
        }
    }

    /**
     * 获取Mqtt账号密码
     */
    public void getMqttAccount() {
        RetrofitManager instance = RetrofitManager.getInstance();
        String sn = new PreferenceWrapper().getStringValue(Constant.SN_7517, "");
        if (TextUtils.isEmpty(sn)) {
            return;
        }
        showWaitDialog(R.string.waiting);
        instance.getData(instance.getApiService().getMqttAccount(sn)//"OGA75172004080001"
                , new RxObserver<BaseResponseBean<MqttAccountBean>>(this, true) {
                    @Override
                    public void onSuccess(BaseResponseBean<MqttAccountBean> responseBean) {
                        cancelWaitingDialog();
                        mqttAccount = responseBean.getData().getUsername();
                        mqttPsw = responseBean.getData().getPassword();
                        connectMqtt(true);
                    }

                    @Override
                    public void onError(String errMsg) {
                        cancelWaitingDialog();
                    }
                }, this);
    }

    private void connectMqtt(boolean isInit) {
        if (TextUtils.isEmpty(mqttAccount) || TextUtils.isEmpty(mqttPsw)) {
            if (!isInit) {
                ToastUtils.showShortToast(this, getString(R.string.no_device_tip));
            }
            return;
        }
        if (MqttManager.getInstance().isConnect()) {
            MqttManager.getInstance().disconnect();
        }
        mHandler.postDelayed(() -> {
            showWaitDialog(R.string.waiting);
            MqttManager.getInstance().connect(mqttAccount, mqttPsw);
            mHandler.postDelayed(() -> {//Mqtt连接超时
                cancelWaitingDialog();
                ToastUtils.showShortToast(this, getString(R.string.mqtt_connect_time_out));
                MqttManager.getInstance().disconnect();
            }, 10 * 1000);
        }, 500);
    }

    /**
     * 显示等待对话框
     *
     * @param strRes
     */
    public void showWaitDialog(int strRes) {
        if (null != waitProgress) {
            if (strRes != 0) {
                waitProgress.setLabel(getString(strRes));
            } else {
                waitProgress.setLabel("");
            }
            if (!waitProgress.isShowing()) {
                waitProgress.show();
            }
        }
    }

    /**
     * 取消等待对话框
     */
    public void cancelWaitingDialog() {
        if (null != waitProgress && waitProgress.isShowing()) {
            waitProgress.dismiss();
        }
    }


    @Override
    public void onBackPressed() {
//        if (currentFragment instanceof MainFragment) {
//            return;
//        }
//        super.onBackPressed();
    }

    @Override
    public void onConnectStateChange(boolean isConnect) {
        mHandler.removeCallbacksAndMessages(null);
        if (isConnect) {
            cancelWaitingDialog();
            String sn = new PreferenceWrapper().getStringValue(Constant.SN_7517, "");
            MqttManager instance = MqttManager.getInstance();
            instance.subscribe(new String[]{"cmd/up/" + sn, "cmd/back/" + sn + "/" + instance.getClientId()}
                    , new int[]{2, 2}, new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            publish(Constant.RUNNING_STATUS_QUERY, "");
                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

                        }
                    });
        } else {
            MassageArmchair.getInstance().setRunningStatus(0);
            MassageArmchair.getInstance().setDeviceStatusBean(null);
            onDeviceStateChange();
        }
    }

    @Override
    public void sendMsgCallback(int state) {
        boolean isWifiNet = currentFragment instanceof WifiNetFragment;
        if (!isWifiNet) {
            cancelWaitingDialog();
            switch (state) {
                case MqttSendMsgCallback.FAIL:
                    ToastUtils.showShortToast(this, getString(R.string.send_command_fail));
                    break;
                case MqttSendMsgCallback.TIMEOUT:
                    ToastUtils.showShortToast(this, getString(R.string.send_command_timeout));
                    break;
                case MqttSendMsgCallback.OFFLINE:
                    ToastUtils.showShortToast(this, getString(R.string.device_offline));
                    break;
            }
        }
    }

    private void showSafetyDialog() {
        if (safetyDialog == null) {
            safetyDialog = new Dialog(this);
            safetyDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
            safetyDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            safetyDialog.setCancelable(false);
            safetyDialog.setContentView(R.layout.dialog_posture_error);
            TextView tvTip = safetyDialog.findViewById(R.id.tv_tip);
            tvTip.setText(R.string.safety_warn);
            TextView tvTipDetail = safetyDialog.findViewById(R.id.tv_tip_detail);
            tvTipDetail.setText(R.string.safety_tip_detail);
            TextView tvConfirm = safetyDialog.findViewById(R.id.tv_re_detect);
            tvConfirm.setText(R.string.clear);
            tvConfirm.setOnClickListener(view -> {
                publish(Constant.ANTI_PINCH_CHECK, "2");
                hideSafeDialog();
            });
        }
        if (!safetyDialog.isShowing() && !isShowSafe) {
            isShowSafe = true;
            safetyDialog.show();
        }
    }

    private void hideSafeDialog() {
        if (safetyDialog != null && safetyDialog.isShowing()) {
            new Handler().postDelayed(() -> isShowSafe = false, 2000);
            safetyDialog.dismiss();
        }
    }

    private void showChildLockDialog() {
        if (childLockDialog == null) {
            childLockDialog = new Dialog(this);
            childLockDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
            childLockDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            childLockDialog.setCancelable(false);
            childLockDialog.setContentView(R.layout.dialog_posture_error);
            TextView tvTip = childLockDialog.findViewById(R.id.tv_tip);
            tvTip.setText(R.string.child_lock);
            TextView tvTipDetail = childLockDialog.findViewById(R.id.tv_tip_detail);
            tvTipDetail.setText(R.string.child_lock_tip);
            TextView tvConfirm = childLockDialog.findViewById(R.id.tv_re_detect);
            tvConfirm.setVisibility(View.GONE);
            tvConfirm.setText(R.string.clear);
            tvConfirm.setOnClickListener(view -> {
//                publish(Constant.ANTI_PINCH_CHECK, "2");
                hideChildLockDialog();
            });
        }
        if (!childLockDialog.isShowing() && !isShowLock) {
            isShowLock = true;
            childLockDialog.show();
        }
    }

    private void hideChildLockDialog() {
        if (childLockDialog != null && childLockDialog.isShowing()) {
            new Handler().postDelayed(() -> isShowLock = false, 2000);
            childLockDialog.dismiss();
        }
    }

    @Override
    public void onDeviceStateChange() {
        runOnUiThread(() -> {
            MassageArmchair instance = MassageArmchair.getInstance();
            DeviceStateBean stateBean = instance.getDeviceStatusBean();
            ivPower.setSelected(instance.getRunningStatus() != 0);
            ivPause.setSelected(instance.getRunningStatus() == 2);
            boolean isSenior = currentFragment instanceof SeniorMassageFragment;
            boolean isAuto = currentFragment instanceof AutoMassageFragment;
            boolean isBodyType = currentFragment instanceof BodyTypeFragment;
            boolean isShoulderType = currentFragment instanceof ShoulderCheckFragment;
            boolean isFault = currentFragment instanceof FaultFragment;
            int detect = 0;
            if (stateBean != null) {
                DeviceStateBean.FunctionsBean.AntiPinchCheckBean antiPinchCheck = stateBean.getFunctions().getAntiPinchCheck();
                if (antiPinchCheck != null) {
                    int safety = Integer.parseInt(antiPinchCheck.getModelValue());
                    if (safety == 1) {
                        showSafetyDialog();
                    } else {
                        hideSafeDialog();
                    }
                }
                boolean isSeniorMassage = MassageArmchair.getInstance().isSeniorMassage();
                if (stateBean.getFunctions().getShoulderDetectCheck() != null) {
                    detect = Integer.parseInt(stateBean.getFunctions().getShoulderDetectCheck().getModelValue());
                    switch (detect) {
                        case 3://检测中
                            if (!isBodyType) {
                                if (isAuto || (isSenior && isSeniorMassage)) {
                                    popBackStack();
                                }
                                if (!inBodyType) {
                                    inBodyType = true;
                                    startToFragmentAddToStack(new BodyTypeFragment());
                                }
                            }
                            break;
                        case 4://检测完成
                            inBodyType = false;
                            inShoulderType = false;
                            if (isShoulderType || isBodyType) {
                                popBackStack();
                            }
                            break;
                        case 5://允许肩部微调
                            if (!isShoulderType) {
                                if (isBodyType) {
                                    popBackStack();
                                }
                                if (!inShoulderType) {
                                    inShoulderType = true;
                                    startToFragmentAddToStack(new ShoulderCheckFragment());
                                }
                            }
                            break;
                        case 0:
                            DeviceStateBean.FunctionsBean.SeatStatusBean seatStatus = stateBean.getFunctions().getSeatStatus();
                            if (seatStatus != null) {
                                int seat = Integer.parseInt(seatStatus.getModelValue());
                                if (seat == 0 && (currentAuto > 0 || isSeniorMassage) && !isBodyType) {
                                    if (!inBodyType) {
                                        inBodyType = true;
                                    }
                                    if (isResume) {
                                        startToFragmentAddToStack(new BodyTypeFragment());
                                    }
                                }
                            }
                            break;
                    }
                }
                if ((detect == 4 || detect == 0) && isSenior && !inSenior) {
                    inSenior = true;
                }
                if ((detect == 4 || detect == 0) && !isSenior && isSeniorMassage && !inSenior) {
                    inSenior = true;
                    startToFragmentAddToStack(new SeniorMassageFragment());
                }
                DeviceStateBean.FunctionsBean.AutoProgramBean autoProgram = stateBean.getFunctions().getAutoProgram();
                if (autoProgram != null) {
                    int auto = Integer.parseInt(autoProgram.getModelValue());
                    if (auto == 0) {//无自动按摩程序
                        running = 0;
                        currentAuto = 0;
//                        inBodyType = false;
//                        inShoulderType = false;
                        if ((isAuto || isBodyType || isShoulderType) && !isSeniorMassage) {
                            popBackStack(MainFragment.class.getName(), 0);
                        }
                    } else {
                        inSenior = false;
                        if (auto != currentAuto) {
                            if (!isBodyType && currentAuto > 0) {
                                inBodyType = false;
                            }
                            if (!isShoulderType && currentAuto > 0) {
                                inShoulderType = false;
                            }
                            currentAuto = auto;
                        }
                        if (auto != running) {
                            if (detect == 4) {
                                running = auto;
                                if (!isAuto) {
                                    if (isSenior) {
                                        popBackStack();
                                    }
                                    startToFragmentAddToStack(new AutoMassageFragment());
                                }
                            }
                        }
                    }
                }
            } else {//关机状态
                running = 0;
                currentAuto = 0;
                inBodyType = false;
                inShoulderType = false;
                inSenior = false;
                if (isAuto || isBodyType || isShoulderType /*|| isSenior*/) {
                    popBackStack(MainFragment.class.getName(), 0);
                }
                DeviceOffBean deviceOffBean = MassageArmchair.getInstance().getDeviceOffBean();
                if (deviceOffBean != null) {
                    DeviceOffBean.FunctionsBean.PowerOffChildLockBean powerOffChildLock
                            = deviceOffBean.getFunctions().getPowerOffChildLock();
                    if (powerOffChildLock != null && Integer.parseInt(powerOffChildLock.getModelValue()) == 1) {//儿童锁
                        showChildLockDialog();
                    } else {
                        hideChildLockDialog();
                    }
                    DeviceOffBean.FunctionsBean.PowerOffPinchBean powerOffPinch
                            = deviceOffBean.getFunctions().getPowerOffPinch();
                    if (powerOffPinch != null && Integer.parseInt(powerOffPinch.getModelValue()) == 1) {//关机防夹
                        showSafetyDialog();
                    } else {
                        hideSafeDialog();
                    }
                }
            }
            String fault = MassageArmchair.getInstance().getFault();
            if (!TextUtils.isEmpty(fault) && !"0".equals(fault) && !isFault && !isInFault) {
                isInFault = true;
                startToFragmentAddToStack(new FaultFragment());
            }
        });
        for (Fragment fragment : manager.getFragments()) {
            if (fragment instanceof BaseFragment) {
                ((BaseFragment) fragment).deviceStateChange();
            }
        }
    }

    public void switchLanguage(String language) {
        //保存设置语言的类型
        new PreferenceWrapper().setStringValueAndCommit(Constant.LANGUAGE, language);
        popBackStack(MainFragment.class.getName(), 1);
        recreate();
    }

    private Context updateResources(Context context) {
        Resources resources = context.getResources();
        String language = new PreferenceWrapper().getStringValue(Constant.LANGUAGE, Constants.ZH);
        Locale locale = null;
        if (Constants.EN.equals(language)) {
            locale = Locale.ENGLISH;
        } else if (Constants.ZH.equals(language)) {
            locale = Locale.CHINESE;
        } else if (Constants.HK.equals(language)) {
            locale = Locale.TRADITIONAL_CHINESE;
        } else {//跟随系统
            locale = Locale.getDefault();
        }
        Context newContext;
        Configuration configuration = resources.getConfiguration();
        if (locale == null) {
            return context;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(locale);
            configuration.setLocales(new LocaleList(locale));
            newContext = context.createConfigurationContext(configuration);
            return newContext;
        } else {
            configuration.setLocale(locale);
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
            return context;
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        Context context = updateResources(newBase);
        super.attachBaseContext(context);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.clear();
        outState.putString("mqttAccount", mqttAccount);
        outState.putString("mqttPsw", mqttPsw);
        outState.putInt("running", running);
        outState.putInt("currentAuto", currentAuto);
        outState.putBoolean("inBodyType", inBodyType);
        outState.putBoolean("inShoulderType", inShoulderType);
        outState.putBoolean("inSenior", inSenior);
        outState.putBoolean("isInFault", isInFault);
        super.onSaveInstanceState(outState);
    }
}
